<?php

namespace app\controllers\api;

use app\models\Material;
use app\models\Member;
use app\models\News;
use app\models\Order;
use app\models\Product;
use app\models\ProductMaterial;
use app\models\User;
use app\models\UserMaterial;
use app\models\UserProduct;
use Yii;
use yii\base\Exception;
use yii\base\UserException;
use yii\web\NotFoundHttpException;

class OrderController extends BaseController {
    // 订单列表
    public function actionList() {
        $user = $this->check();
        $models = Order::find()
            ->andWhere([
                'trader_id' => $user->id,
            ])
            ->orWhere([
                'provider_id' => $user->id,
            ])
            ->all();
        $this->log('订单 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }

    // 在售产品
    public function actionOnSaleList($name = '') {
        $user = $this->check();
        $models = UserProduct::find()
            ->andFilterWhere([
                'name' => $name,
            ])
            ->andWhere(['<>', 'user_id', $user->id,])
            ->all();
        $this->log('原料 - 查询列表', '');
        return $this->renderSuccess([
            'list' => $models,
        ]);
    }

    // 定价产品
    public function actionCreate() {
        $user = $this->check();
        $this->checkModify();
        $id = Yii::$app->request->post('id');
        $product = UserProduct::findOne($id);
        if(!$product) {
            throw new UserException('选择产品不存在');
        }

        $price = (double)Yii::$app->request->post('price');
        if($price<=0) {
            throw new UserException('定价错误');
        }
        $num = (int)Yii::$app->request->post('num');
        if($num<=0) {
            throw new UserException('购买数量错误');
        }
        if($user->role != User::ROLE_ADMIN) {
            $member_id = (int)Yii::$app->request->post('member_id');
            $member = Member::findOne($member_id);
            if(!$member || $member->user_id != $user->id) {
                throw new UserException('未选择企业成员');
            }
            if($member->position != Member::POSITION_CMO) {
                throw new UserException('选择的企业成员职位不正确');
            }
        }

        // $this->transaction(function() use ($price, $userProduct, $user) {
        //     $userProduct->sale_price = round($price, 2);
        //     $userProduct->save();
        // });

        $order = new Order();
        $order->product_id = $product->product_id;
        $order->unit_price = $price;
        $order->sale_num = $num;
        $order->order_price = round($price * $num, 2);
        if($user->country_id != $product->user->country_id) {
            $order->import_duty = $order->order_price * $user->country->import_duty;
            $order->export_tax = $order->order_price * $product->user->country->export_tax;
        } else {
            $order->import_duty = 0;
            $order->export_tax = 0;
        }
        $order->status = Order::STATUS_CREATE;
        $order->remark = '';
        $order->provider_id = $product->user_id;
        $order->provider_member_id = null;
        $order->trader_id = $user->id;
        if($user->role != User::ROLE_ADMIN) {
            $order->trader_member_id = $member->id;
        }
        $order->order_time = date('Y-m-d H:i:s');

        $order->save();
        $this->log('产品 - 下单', $order->id);
        return $this->renderSuccess([
            'model' => $order,
        ]);
    }

    // 订单取消
    public function actionCancel() {
        $user = $this->check([]);
        $this->checkModify();
        $id = Yii::$app->request->post('id');
        $member_id = (int)Yii::$app->request->post('member_id');
        $model = Order::findOne($id);
        if(!$model || $model->trader_id != $user->id) {
            throw new UserException('不是本人的订单无法操作');
        }
        if($model->status != Order::STATUS_CREATE) {
            throw new UserException('该状态无法取消');
        }
        $model->provider_member_id = $member_id;
        $model->status = Order::STATUS_CANCEL;
        $model->save();
        $this->log('订单 - 取消', $model->id);
        return $this->renderSuccess([]);
    }

    // 订单拒绝
    public function actionReject() {
        $user = $this->check([]);
        $this->checkModify();
        $id = Yii::$app->request->post('id');
        $member_id = (int)Yii::$app->request->post('member_id');
        $model = Order::findOne($id);
        if(!$model || $model->provider_id != $user->id) {
            throw new UserException('不是本人的订单无法操作');
        }
        if($model->status != Order::STATUS_CREATE) {
            throw new UserException('该状态无法拒绝');
        }
        $model->provider_member_id = $member_id;
        $model->status = Order::STATUS_REJECT;
        $model->save();
        $this->log('订单 - 拒绝', $model->id);
        return $this->renderSuccess([]);
    }

    // 订单确认
    public function actionConfirm() {
        $user = $this->check([]);
        $this->checkModify();
        $id = Yii::$app->request->post('id');
        $model = Order::findOne($id);
        if(!$model || $model->provider_id != $user->id) {
            throw new UserException('不是本人的订单无法操作');
        }
        if($model->status != Order::STATUS_CREATE) {
            throw new UserException('该状态无法取消');
        }

        $member_id = (int)Yii::$app->request->post('member_id');
        $member = Member::findOne($member_id);
        if(!$member || $member->user_id != $user->id) {
            throw new UserException('未选择企业成员');
        }
        if($member->position != Member::POSITION_CMO) {
            throw new UserException('选择的企业成员职位不正确');
        }
        $model->provider_member_id = $member_id;

        $this->transaction(function() use($model) {
            $model->status = Order::STATUS_FINISH;
            $traderProduct = UserProduct::getByProduct($model->product, $model->trader);
            $providerProduct = UserProduct::getByProduct($model->product, $model->provider);
            if($providerProduct->num < $model->sale_num) {
                throw new UserException('库存不足');
            }
            $traderProduct->num += $model->sale_num;
            $traderProduct->save();
            $providerProduct->num -= $model->sale_num;
            $providerProduct->save();

            $this->logForUser($model->provider, '订单 - 确认', $model->id, $model->order_price - $model->export_tax);
            $this->logForUser($model->trader, '订单 - 确认', $model->id, -($model->order_price + $model->import_duty));
            $model->providerMember->commission = round($model->providerMember->commission + $model->order_price * 0.03, 2);
            $model->providerMember->save();
            if($model->traderMember) {
                $model->traderMember->commission = round($model->traderMember->commission + $model->order_price * 0.03, 2);
                $model->traderMember->save();
            }

            $providerGov = User::findOne([
                'country_id' => $model->provider->country_id,
                'role' => User::ROLE_GOV,
            ]);
            $this->logForUser($providerGov, '订单 - 确认', $model->id, $model->export_tax);
            $traderGov = User::findOne([
                'country_id' => $model->trader->country_id,
                'role' => User::ROLE_GOV,
            ]);
            $this->logForUser($traderGov, '订单 - 确认', $model->id, $model->import_duty);

            $model->pay_time = date('Y-m-d H:i:s');

            $model->save();
        });
        $this->log('订单 - 确认', $model->id);
        return $this->renderSuccess([]);
    }
}
